package com.example.demo.service.imp;

import com.example.demo.dao.DeviceDao;
import com.example.demo.entity.Device;
import com.example.demo.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Date:2021/7/1 22:32
 * @Author:郑伟
 * @Version:1.1.0
 */
@Service
public class DeviceServiceImp implements DeviceService {
    @Autowired
    DeviceDao deviceDao;
    @Override
    public Device saveDevice(Device device) {
        return deviceDao.save(device);
    }

    public Optional<Device> findById(Integer id){

        Optional<Device> device=deviceDao.findById(id);
        return device;
    }
//

    public List<Device> findAll(){

        List<Device> myList=deviceDao.findAll();
        return myList;
    }

    public Page<Device> findByPage(int pageIndex, int pageSize){

        Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Device> myList=deviceDao.findAll(pageable);

        return myList;

    }




//    public Device add(Device device){
//        deviceDao.save(device);
//        return device;
//    }
//
//    public Device update(Device device){
//        Device deviceOld=deviceDao.getOne(device.getId());
//        //todo sth....
//        deviceDao.save(device);
//        return device;
//    }


    public int delete(Device device){

        try{

            deviceDao.delete(device);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    public  int delete(Integer id){
        Device device=deviceDao.getOne(id);

        return delete(device);

    }
}
